import React from 'react';
import Api from 'Utils/api';
import { generateUUID } from 'Utils/index';
import * as routerActions from 'react-router-redux';
import { connect } from 'react-redux';
import { List, InputItem, TextareaItem, WhiteSpace } from 'antd-mobile';
import LittleButton from 'Component/Page/CommonComponents/LittleButton';
// import { reset } from 'Actions/businessAction';
import message from 'Utils/message';
import dialog from 'Utils/dialog';
import BottomButton from '../../BottomButton';
import './index.scss';

const CaptchaSeconds = 60;
class AppointmentPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      complaints: '',
      name: '',
      idCard: '',
      phone: '',
      code: '',
      content: '',
      money: [],
      lawPerson1: {},
      lawPerson2: {},
      businessInfo: {
        id: props.businessInfo.id,
        name: props.businessInfo.name,
        type: props.businessInfo.type,
      },
      remainingSecond: CaptchaSeconds,
    }
    this.canSendCaptcha = true;
    this.countDownSeconds = ::this.countDownSeconds;
    this.sendCaptcha = ::this.sendCaptcha;
    this.changeMerchant = ::this.changeMerchant;
    this.changeComplaints = ::this.changeComplaints;
    this.changeMerchantType = ::this.changeMerchantType;
    this.changeContent = ::this.changeContent;
    this.changeName = ::this.changeName;
    this.changeIdCard = ::this.changeIdCard;
    this.changePhone = ::this.changePhone;
    this.changeCode = ::this.changeCode
    this.showLawPerson = ::this.showLawPerson;
    this.isok = ::this.isok;
    this.submitHandle = ::this.submitHandle;
    this.randomBusiness = ::this.randomBusiness;
  }
  componentWillUnmount() {
    clearInterval(this.timer);
    this.canSendCaptcha = true;
  }
  /**
   * 验证码倒计时
   */
  countDownSeconds() {
    const remainingSecond = this.state.remainingSecond - 1;
    if (remainingSecond < 0) {
      this.canSendCaptcha = true;
      clearInterval(this.timer);
      this.timer = undefined;
    } else {
      if (!this.timer) {
        this.timer = setInterval(this.countDownSeconds, 1000);
      }
      this.setState(preState => (Object.assign({}, preState, {
        remainingSecond,
      })));
    }
  }
  /**
   * 发送验证码
   */
  sendCaptcha() {
    const { phone } = this.state;
    if (!this.canSendCaptcha) {
      return;
    }
    this.canSendCaptcha = false;
    setTimeout(() => {
      this.setState({
        remainingSecond: CaptchaSeconds,
      }, () => {
        this.countDownSeconds();
      });
    }, 0);
    const self = this;
    const api = new Api({
      method: 'POST',
      path: '/phone/verify_code',
      data: {
        phone,
      },
      error: () => {
        self.setState({
          remainingSecond: 0,
        }, () => {
          self.canSendCaptcha = true;
          clearInterval(this.timer);
          this.timer = undefined;
        });
      },
    });
    api.run();
  }
  changeMerchantType(val) {
    this.setState({
      merchantType: val[0],
    });
  }
  changeComplaints(val) {
    this.setState({
      complaints: val,
    });
  }
  changeContent(val) {
    this.setState({
      content: val,
    });
  }
  changeName(val) {
    this.setState({
      name: val,
    });
  }
  changeIdCard(val) {
    this.setState({
      idCard: val,
    });
  }
  changePhone(val) {
    this.setState({
      phone: val,
    });
  }
  changeCode(val) {
    this.setState({
      code: val,
    });
  }
  showLawPerson() {
    const { businessInfo, complaints } = this.state;
    if (!businessInfo.id) {
      message.open('请先选择商家');
      return;
    }
    const self = this;
    const api = new Api({
      method: 'GET',
      path: `/justices/random/${businessInfo.id}`,
      query: {
        evade_executor: complaints,
      },
      success: (persons) => {
        if (persons.length > 0) {
          self.setState({
            lawPerson1: {
              id: persons[0].id,
              name: persons[0].name,
            },
            lawPerson2: {
              id: persons[1].id,
              name: persons[1].name,
            },
          });
        }
      },
    });
    api.run();
  }
  changeMerchant(val) {
    this.setState({
      merchant: val,
    })
  }
  isok() {
    const {
      businessInfo,
      name,
      idCard,
      phone,
      code,
      lawPerson1,
      lawPerson2,
      content,
    } = this.state;
    return (
      businessInfo.id > 0
      && name
      && idCard
      && phone
      && code
      && lawPerson1
      && lawPerson2
      && content);
  }
  clear() {
    this.setState({
      complaints: '',
      name: '',
      idCard: '',
      phone: '',
      code: '',
      content: '',
      money: [],
      lawPerson1: {},
      lawPerson2: {},
      businessInfo: {
        id: '',
        name: '',
        type: '',
      },
      remainingSecond: 0,
    })
  }
  submitHandle() {
    const { businessInfo, complaints, name, idCard, phone, code,
      lawPerson1, lawPerson2, content } = this.state;
    const self = this;
    const api = new Api({
      method: 'POST',
      path: '/randoms/user',
      data: {
        company_name: businessInfo.name,
        type: businessInfo.type,
        evade_executor: complaints,
        law_executor1: lawPerson1.name,
        law_executor2: lawPerson2.name,
        name,
        is_anonymity: false,
        id_no: idCard,
        phone,
        code,
        content,
        uuid: generateUUID(),
      },
      success: () => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => { self.props.dispatch(routerActions.goBack()); },
          },
        ];
        dialog.open('提示', '提交预约成功', buttons, 'center');
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  randomBusiness() {
    const self = this;
    const api = new Api({
      method: 'GET',
      path: '/enterprises/random',
      success: (json) => {
        self.setState({
          businessInfo: json,
        });
      },
    });
    api.run();
  }
  render() {
    const { complaints, name, idCard, phone, code, remainingSecond,
      lawPerson1, lawPerson2, content, businessInfo } = this.state;
    return (
      <div className="big-body">
        <div className="Inform">
          <div className="Inform-title">
            <span>我要预约</span>
          </div>
          <List className="appointment-list">
            <InputItem
              placeholder="请选择商家"
              type="string"
              disabled
              value={businessInfo.name}
              onChange={this.changeMerchant}
              className="business-name"
            >
              商家名称
              <LittleButton
                title="选择商家"
                width={128}
                height={50}
                onClick={() => {
                  this.props.dispatch(routerActions.push('/select_business'));
                }}
                className="little-button big-font double-input"
              />
              <LittleButton
                title="随机商家"
                width={128}
                height={50}
                className="little-button big-font in-input"
                onClick={this.randomBusiness}
              />
            </InputItem>
            <InputItem
              placeholder="请输入回避人员姓名"
              type="string"
              value={complaints}
              onChange={this.changeComplaints}
            >
              回避人员
            </InputItem>
            <InputItem
              placeholder="请选择执法人员姓名"
              disabled
              type="string"
              className="random-person"
              value={lawPerson1.name || ''}
            >
              执法人员
              <LittleButton
                title="随机人员"
                width={128}
                height={50}
                onClick={this.showLawPerson}
                disabled={!businessInfo.id}
                className="little-button big-font in-input"
              />
            </InputItem>
            <InputItem
              placeholder="请选择执法人员姓名"
              disabled
              type="string"
              value={lawPerson2.name || ''}
            >
              {' '}
            </InputItem>
          </List>
          <WhiteSpace />
          <List className="my-list">
            <InputItem
              placeholder="请输入姓名"
              type="string"
              value={name}
              onChange={this.changeName}
            >
              申请人姓名
            </InputItem>
            <InputItem
              placeholder="请输入身份证号"
              type="string"
              value={idCard}
              onChange={this.changeIdCard}
            >
              身份证号码
            </InputItem>
            <InputItem
              placeholder="请输入联系电话"
              type="string"
              value={phone}
              onChange={this.changePhone}
            >
              联系电话
              <LittleButton
                title={remainingSecond === 60 || remainingSecond === 0
                  ? '获取验证码'
                  : `剩余${remainingSecond}s`
                }
                width={200}
                height={60}
                disabled={!phone}
                onClick={this.sendCaptcha}
                className="little-button big-font in-input"
              />
            </InputItem>
            <InputItem
              placeholder="请输入验证码"
              type="string"
              value={code}
              onChange={this.changeCode}
            >
              验证码
            </InputItem>
          </List>
          <WhiteSpace />
          <div className="content">
            <div className="content-title">内容</div>
            <TextareaItem
              rows={5}
              count={140}
              value={content}
              onChange={this.changeContent}
              placeholder="请输入内容"
            />
          </div>
        </div>
        <BottomButton
          okText="提交"
          disabled={!this.isok()}
          okHandle={this.submitHandle}
        />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    businessInfo: state.businessReducer,
  };
}

export default connect(mapStateToProps)(AppointmentPage);
